#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 28 déc. 2011

@author: nathanael


Provide some utilitis for regex

'''



class PatternFactoryI(object):
    """Base object used to build regex pattern from a string.
    """
    def build_regex(self, string):
        """Build string pattern valid as regard of regular expression. 
        """
        raise NotImplementedError

class RegexPattern(PatternFactoryI):
    "Is identity for the given strinf is a a valid regex."
    def build_regex(self, string):
        return string

class WordPattern(PatternFactoryI):
    "Match only word"
    def build_regex(self, word):
        return ".*([ \\(]|^)" + word + "([ \.,;:!\\)]|$).*"

class CustomWordPattern(WordPattern):
    """Match word with language notion
    
    Tools to build regex pattern for language with tools for 
    case sensitive and emphasis characters. 
    """
    def __init__(self,
                 whole_word=True,
                 case_sensitive=True,
                 emphasis_characters=()):
        self.whole_word = whole_word
        self.case_sensitive = case_sensitive
        self.emphasis_characters = emphasis_characters


    def build_regex(self, string):
        # split list into a list
        # All char of initial string must be a list's elements at all step.
        # eg:
        # 'string'
        # -> ('s', 't', 'r', 'iïî', 'n', 'g')
        # -> ('sS', 'tT', 'rR', 'iïîIÏÎ', 'nN', 'gG')
        patter_l = list(string)

        # replace an emphasis character by all equivalent char.
        # eg (e -> eéèêë, à -> aàâ) 
        if self.emphasis_characters:
            char_list = []
            for char in string:
                c = char
                for emphasis in self.emphasis_characters:
                    if char in emphasis:
                        c = emphasis
                char_list.append(c)
            patter_l = char_list

        # replace list's element by colaptse of lower and upper string 
        # eg. 'String' -> 'stringSTRING'
        if not self.case_sensitive:
            patter_l = ["%s%s" % (s.lower(), s.upper())
                        for s in patter_l]

        # replace all list's element by regex group "[...]". This group 
        # corresponding at a initial char of string. 
        pattern = ''.join(map(lambda s: "[%s]" % s, patter_l))
        if self.whole_word:
            pattern = WordPattern.build_regex(self, pattern)
        else:
            pattern = ".*" + pattern + ".*"

        return pattern
